package com.gitee.ricesugar.mall.model.Service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.gitee.ricesugar.mall.model.DAO.OrderDAO;
import com.gitee.ricesugar.mall.model.POJO.DO.CartItemDO;
import com.gitee.ricesugar.mall.model.POJO.DO.OrderDO;
import com.gitee.ricesugar.mall.model.POJO.DTO.CartItemDTO;
import com.gitee.ricesugar.mall.model.POJO.DTO.OrderDTO;

import java.sql.SQLException;
import java.util.ArrayList;

public class OrderService {

    private OrderDAO orderDAO;

    public OrderService() throws SQLException, ClassNotFoundException {
        orderDAO = new OrderDAO();
    }

    public void buyList(ArrayList<CartItemDTO> cart) throws SQLException, JsonProcessingException {
        ArrayList<CartItemDO> items = new ArrayList<>();
        for (CartItemDTO item : cart){
            CartItemDO it = new CartItemDO(item.getId(), item.getUsername(), item.getAmount());
            items.add(it);
        }
        orderDAO.buyList(items);
    }

    public void buyItem(CartItemDTO item) throws SQLException {
        CartItemDO it = new CartItemDO(item.getId(), item.getUsername(), item.getAmount());
        orderDAO.buyItem(it);
    }

    public ArrayList<OrderDTO> listOrder(String username) throws SQLException {
        ArrayList<OrderDO> orderDO = orderDAO.listOrder(username);
        ArrayList<OrderDTO> orderDTO = new ArrayList<>();
        for(OrderDO order : orderDO){
            orderDTO.add(new OrderDTO(order.getId(), order.getDate(), order.getItems()));
        }
        return orderDTO;
    }
}
